package com.example.scaletest.activity;

import android.app.IntentService;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import com.example.scaletest.bean.BindData;
import com.example.scaletest.db.DataBaseHelper;
import com.example.scaletest.db.DataDao;
import com.example.scaletest.utils.NetConnHelper;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * Created by LK on 2016/10/20.
 */
public class NetWorkService extends IntentService {
    private DataDao dataDao;
    //public String UPLOAD_API="http://10.103.240.141:8080/upload";
    public String UPLOAD_API = "http://10.103.246.33:8080/data/bindingEpcAndGoods"; //http://139.220.193.149/test2/api/bidingDeviceAndGoods";
    private HttpURLConnection conn = null;
    private String finalResult = "";
    private String  request;
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     *
     */
    public NetWorkService() {
        super("NetWorkService");
    }

    public NetWorkService(String name) {
        super(name);
    }

    @Override
    public void onCreate() {
        dataDao = DataDao.getInstance(NetWorkService.this);
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(this.getClass().getName(), "onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    public void postToUIThread(String message){
        final String mes = message;
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), mes, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String result = "";
        request = intent.getExtras().getString("request");
        List<BindData> bindDatas = dataDao.getBindData();
        if (bindDatas.size()>0){
            if (NetConnHelper.isConn(NetWorkService.this)){
                try {
                    result = uploadData(bindDatas,UPLOAD_API);
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.has("result")){
                        if (jsonObject.getBoolean("result")){
                            postToUIThread("上传成功");
                            dataDao.deleteBindData();
                        }else {
                            postToUIThread("上传出错");
                        }
                    }else {
                        postToUIThread("上传出错");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    postToUIThread("上传失败");
                }
            }else {
                postToUIThread("没有网络，请检查网络情况");
            }

        }else {
            postToUIThread("没有上传数据");
        }
    }

    public String uploadData(List<BindData> bindDatas,String url) throws Exception {
//        JSONArray jsonArray = new JSONArray();
        //String request;
        JSONObject jsonObject = new JSONObject();
        //request = intent.getExtras().getString("request");
        for (BindData bindData : bindDatas){
            jsonObject.put(DataBaseHelper.BATCH_ID,bindData.getBatchId());
            jsonObject.put(DataBaseHelper.DEVICE_ID,bindData.getDeviceId());
            jsonObject.put(DataBaseHelper.GOODS_ID,bindData.getGoodsId());

//            jsonArray.put(jsonObject);
        }
        JSONObject jsonList = new JSONObject(request);
        jsonObject.put("firm_id",jsonList.getString("firm_id"));

//        JSONObject finalJson = new JSONObject();
//        finalJson.put("data",jsonArray);
//        String data = finalJson.toString();
        String data = jsonObject.toString();
        String result = sendData(data,url);
        Log.d("NetWorkService",result);
        return result;
    }

    public String sendData(String data,String url){
        BufferedReader reader;
        OutputStreamWriter writer;
        Log.i("Request", "start http request:" + url);
        try {
            conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestProperty("content-type", "application/json;charset=utf-8");
            //这个writer会把data写到http正文里
            writer = new OutputStreamWriter(conn.getOutputStream());
            writer.write(data);
            writer.flush();
            writer.close();

            //getInputStream开始真正发送
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) !=null){
                result.append(line);
            }
            finalResult = result.toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            if (conn != null){
                conn.disconnect();
            }
        }
        return finalResult;
    }
}
